Skip to main content

Conditions

  1. If any command runs successfully inside if conditional expression then if treats it as true.
if print; then echo "foo"; else echo "bar"; fi
  1. There's a command called test to evaluate conditional expression.
if test $a -ge $b;
then
echo "a is bigger";
else
echo "b is bigger";
fi

see the test command ? It evaluates the conditional expression and return true / false based on the evaluation.

  1. test is later replaced with [.
if [ $a -ge $b ];
then
echo "a is big";
else
echo "b is big";
fi

Yes, the command is [ and it starts evaluating the expression until it gets ]. You can check it yourself with which [ or even man [. [ is basically another representation of test command.

  1. There's some limitations of using [ or test. For example, it can't evaluate &&, ||. So here comes [[ with improvements.
if [[ $a > $b || $a == $b ]]; 
then
echo "a is big";
else
echo "b is big";
fi

You can also read more about the differences between [ and [[ from here.

  1. There's no ternary operator in bash. But there's a hack ...
[[ $a == $b ]] && echo "Equal" || echo "Not equal"
  1. One Liner
if [ -d "/var/www/html/" ]; then echo "html Directory exists"; else echo "html Directory not exist "; fi